<template>
  <div class="dashboard-container">
    <div><h1>Smart Shift Book Machining</h1></div>
    <hr/>
    <div class="container">
      <div class="tableBar">
        <div>
          <el-form :inline="true" :model="ruleForm" :rules="rules" label-width="120px">
            <el-form-item label="Date/填写日期">
              <el-input v-model="ruleForm.currentDate" readonly></el-input>
            </el-form-item>
            <el-form-item label="Weekday/星期">
              <el-input v-model="ruleForm.currentWeekDay" readonly></el-input>
            </el-form-item>
            <el-form-item label="Line/产线">
              <el-input v-model="ruleForm.line" readonly></el-input>
            </el-form-item>
            <el-form-item label="Group/班组">
              <el-radio-group v-model="ruleForm.group">
                <el-radio label="A"></el-radio>
                <el-radio label="B"></el-radio>
                <el-radio label="C"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="Shift/班次">
              <el-select v-model="ruleForm.selectedShift" clearable placeholder="请选择班次" @change="handleShiftChange" @clear="clearSelection">
                <el-option v-for="item in ruleForm.shiftOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-form :inline="true" :model="ruleForm">
            <el-form-item label="Part No./料号1">
              <el-select v-model="ruleForm.PartNo1" filterable clearable placeholder="请选择料号1" @change="updatePartNo(1)" @clear="clearPartNo(1)">
                <el-option v-for="item in ruleForm.PartNos"
                           :key="item.partNumber"
                           :label="item.partNumber"
                           :value="item.partNumber"
                           :disabled="isDisabled(1, item.partNumber)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="Part No./料号2">
              <el-select v-model="ruleForm.PartNo2" filterable clearable placeholder="请选择料号2" @change="updatePartNo(2)" @clear="clearPartNo(2)">
                <el-option v-for="item in ruleForm.PartNos"
                           :key="item.partNumber"
                           :label="item.partNumber"
                           :value="item.partNumber"
                           :disabled="isDisabled(2, item.partNumber)"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="info-box" style="margin-bottom: 10px">
            <div class="fixed-size1">
              <div class="info-item">
                <span><strong>CT: </strong></span>
                <span :data-value="ruleForm.CT1"> {{ ruleForm.CT1 }} </span>
              </div>
              <div class="info-item">
                <span><strong>FinalCustomer: </strong></span>
                <span :data-value="ruleForm.finalCustomer1"> {{ ruleForm.finalCustomer1 }} </span>
              </div>
              <div class="info-item">
                <span><strong>Project: </strong></span>
                <span :data-value="ruleForm.project1"> {{ ruleForm.project1 }} </span>
              </div>
            </div>
            <div class="fixed-size2">
              <div class="info-item">
                <span><strong>CT: </strong></span>
                <span :data-value="ruleForm.CT2"> {{ ruleForm.CT2 }} </span>
              </div>
              <div class="info-item">
                <span><strong>FinalCustomer: </strong></span>
                <span :data-value="ruleForm.finalCustomer2"> {{ ruleForm.finalCustomer2 }} </span>
              </div>
              <div class="info-item">
                <span><strong>Project: </strong></span>
                <span :data-value="ruleForm.project2"> {{ ruleForm.project2 }} </span>
              </div>
            </div>
          </div>
        </div>
        <!-- 下面是填写班次报表的表格 -->
        <div>
          <el-table class="ShiftBookTable" border style="width: 100%" :data="ruleForm.tableData" height="600">
            <el-table-column fixed prop="timeSlot" label="Period/时间段" width="150"></el-table-column>
            <el-table-column prop="partNo1" label="Part No./料号1" width="220">
              <template slot-scope="scope">
                <el-select v-model="scope.row.partNo1" filterable placeholder="请选择" clearable style="width: 170px">
                  <el-option v-for="item in ruleForm.tablePartNo1"
                             :key="item"
                             :label="item"
                             :value="item">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="output1" label="产出1" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.output1" style="width: 90px" clearable placeholder="产出1" @input="calculateTotal(scope.row)"></el-input> /pcs
              </template>
            </el-table-column>
            <el-table-column prop="partNo2" label="Part No./料号2" width="220">
              <template slot-scope="scope">
                <el-select v-model="scope.row.partNo2" filterable placeholder="请选择" clearable style="width: 170px">
                  <el-option v-for="item in ruleForm.tablePartNo2"
                             :key="item"
                             :label="item"
                             :value="item">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="output2" label="产出2" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.output2" style="width: 90px" clearable placeholder="产出2" @input="calculateTotal(scope.row)"></el-input> /pcs
              </template>
            </el-table-column>
            <el-table-column prop="actualOutput" label="Actual/实际总产出" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.actualOutput" style="width: 90px" readonly placeholder="总产出"></el-input> /pcs
              </template>
            </el-table-column>
            <el-table-column prop="reason1" label="Reason1/原因1" width="200">
              <template slot-scope="scope">
                <el-cascader
                  v-model="scope.row.reason1"
                  :options="ruleForm.reasons"
                  :props="{ expandTrigger: 'hover' }"
                  placeholder="原因1"
                  style="width: 150px"
                  clearable></el-cascader>
              </template>
            </el-table-column>
            <el-table-column prop="downTime1" label="停机时长1" width="165">
              <template slot-scope="scope">
                <el-input v-model="scope.row.downTime1" placeholder="时长1" clearable style="width: 85px"></el-input> /min
              </template>
            </el-table-column>
            <el-table-column prop="reason2" label="Reason2/原因2" width="200">
              <template slot-scope="scope">
                <el-cascader
                  v-model="scope.row.reason2"
                  :options="ruleForm.reasons"
                  :props="{ expandTrigger: 'hover' }"
                  placeholder="原因2"
                  style="width: 150px"
                  clearable></el-cascader>
              </template>
            </el-table-column>
            <el-table-column prop="downTime2" label="停机时长2" width="165">
              <template slot-scope="scope">
                <el-input v-model="scope.row.downTime2" placeholder="时长2" clearable style="width: 85px"></el-input> /min
              </template>
            </el-table-column>
            <el-table-column prop="reason3" label="Reason3/原因3" width="200">
              <template slot-scope="scope">
                <el-cascader
                  v-model="scope.row.reason3"
                  :options="ruleForm.reasons"
                  :props="{ expandTrigger: 'hover' }"
                  placeholder="原因3"
                  style="width: 150px"
                  clearable></el-cascader>
              </template>
            </el-table-column>
            <el-table-column prop="downTime3" label="停机时长3" width="165">
              <template slot-scope="scope">
                <el-input v-model="scope.row.downTime3" placeholder="时长3" clearable style="width: 85px"></el-input> /min
              </template>
            </el-table-column>
            <el-table-column prop="downTimeTotal" label="Duration/停机时长" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.downTimeTotal" placeholder="总时长" style="width: 100px"></el-input> /min
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="subBox">
          <el-button type="primary" @click="submitShiftBook">提交</el-button>
          <el-button type="primary" @click="submitShiftBook">保存并继续添加报表</el-button>
          <el-button @click="() => this.$router.push('/shiftbook')">返回</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { getCTAndCustomer, getDowntimeReason, getPartNumberByLine } from '@/api/line'

export default {
  data() {
    return {
      ruleForm: {
        currentDate: new Date().toLocaleDateString(),
        currentWeekDay: this.getWeekDay(new Date()),
        line: this.$route.query.line,
        group: '',
        shiftOptions: [
          { label: '晚班8H 00:00-08:00', value: '00:00 -08:00' },
          { label: '早班8H 08:00-16:00', value: '08:00 -16:00' },
          { label: '中班8H 16:00-24:00', value: '16:00 -24:00' }
        ],
        tableData: [],
        //料号1相关选择器数据
        PartNo1: '',
        CT1:'',
        finalCustomer1:'',
        project1:'',
        //料号2相关选择器数据
        PartNo2: '',
        CT2:'',
        finalCustomer2:'',
        project2:'',
        //班次选择器数据
        selectedShift: '',
        //选项数据
        PartNos: [],
        //选项数据
        reasons: [],
        tablePartNo1: [],
        tablePartNo2: [],
        //料号1选择数据
        PartNo1Customer: [],
        //料号2选择数据
        PartNo2Customer: [],
      },
      rules: {
        selectedShift: [
          {required: true, message: '请选择一个班次', trigger: 'blur'},
        ]
      }

    }
  },
  computed: {
  },
  created() {
    getPartNumberByLine({line: this.ruleForm.line}).then(res => {
      this.ruleForm.PartNos = res.data.data
    })
    getDowntimeReason({department: this.$route.query.department, line: this.ruleForm.line}).then(res => {
      const data = res.data.data;
      this.ruleForm.reasons = this.transformToCascader(data);
    })
  },

  methods: {
    //提交shiftbook表单数据
    submitShiftBook() {
      const tableLoad = this.ruleForm.tableData.map(item => ({
        line: this.ruleForm.line,
        bdate: this.ruleForm.currentDate,
        weekday: this.ruleForm.currentWeekDay,
        bweek: '',
        bgroup: this.ruleForm.group,
        bshift: this.ruleForm.selectedShift,
        partno: '',
        cuspro: '',
        CT: '',
        operatorEmpno: '',
        operatorName: '',
        nowTime: '',
        Station: '',
        loginempno: '',
        loginname: '',
        part: '',
        FinalCustomer: '',
        Segment: '',
        GroupT: '',
        PartType: '',
        sLine: '',
        Item: '',
        CostCenter: '',
        Customer: '',
        Project: '',
        dmPs: '',
        downAB: '',
        timeSlot: item.timeSlot,
        partNo: item.partNo1,
        output1: item.output1,
        partNo2: item.partNo2,
        output2: item.output2,
        downTimeTotal: item.downTimeTotal,
        downTime1: item.downTime1,
        reason1: item.reason1,
        downTime2: item.downTime2,
        reason2: item.reason2,
        downTime3: item.downTime3,
        reason3: item.reason3,
      }))
      console.log('表单数据：',tableLoad);
    },
    transformToCascader(data) {
      const groupMap = new Map();
      data.forEach((item) => {
        const code = item.downtime_Code;
        groupMap.has(code) || groupMap.set(code, []);
        groupMap.get(code).push(item);
      });
      return Array.from(groupMap).map(([code, items]) => ({
        value: code,
        label: `故障代码 ${code}`,
        children: items.map(child => ({
          value: child.downtime_Reason,
          label: child.downtime_Reason
        }))
      }));
    },
    getWeekDay(date) {
      const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      return weekDays[date.getDay()];
    },
    handleShiftChange(shiftValue) {
      this.ruleForm.tablePartNo1 = [];
      this.ruleForm.tablePartNo2 = [];
      // 解析时间段
      const [start, end] = shiftValue.split('-');
      // 生成小时段列表
      const timeSlots = this.generateTimeSlots(start, end);
      // 构建表格数据
      this.ruleForm.tableData = timeSlots.map(slot => ({
        timeSlot: slot,
        partNo1: this.ruleForm.PartNo1,
        partNo2: this.ruleForm.PartNo2,
        // 可添加其他字段
      }));
      this.ruleForm.tablePartNo1.push(this.ruleForm.PartNo1);
      this.ruleForm.tablePartNo2.push(this.ruleForm.PartNo2);

    },
    updatePartNo(type){
      this.ruleForm.tableData.forEach(row => {
        if (type === 1) {
          row.partNo1 = this.ruleForm.PartNo1;
        } else {
          row.partNo2 = this.ruleForm.PartNo2;
        }
      })
      if (type === 1) {
        this.ruleForm.tablePartNo1 = [];
        this.ruleForm.tablePartNo1.push(this.ruleForm.PartNo1);
        getCTAndCustomer({equipment: this.ruleForm.line, partNumber: this.ruleForm.PartNo1}).then(res => {
          const data = res.data.data;
          this.ruleForm.CT1 = data.cycle_Time;
          this.ruleForm.finalCustomer1 = data.final_Customer;
          this.ruleForm.project1 = data.project;
        })
      } else {
        this.ruleForm.tablePartNo2 = [];
        this.ruleForm.tablePartNo2.push(this.ruleForm.PartNo2);
        getCTAndCustomer({equipment: this.ruleForm.line, partNumber: this.ruleForm.PartNo2}).then(res => {
          const data = res.data.data;
          this.ruleForm.CT2 = data.cycle_Time;
          this.ruleForm.finalCustomer2 = data.final_Customer;
          this.ruleForm.project2 = data.project;
        })
      }
    },
    clearPartNo(type) {
      if (type === 1) {
        this.ruleForm.CT1 = '';
        this.ruleForm.finalCustomer1 = '';
        this.ruleForm.project1 = '';
      } else {
        this.ruleForm.CT2 = '';
        this.ruleForm.finalCustomer2 = '';
        this.ruleForm.project2 = '';
      }
    },
    clearSelection() {
      this.ruleForm.selectedShift = '';
      this.ruleForm.tableData= [];
    },
    // 生成时间段数组（支持跨天）
    generateTimeSlots(startTime, endTime) {
      const slots = [];
      const start = this.timeToMinutes(startTime);
      let end = this.timeToMinutes(endTime);

      // 处理跨天情况
      if (end < start) end += 24 * 60;

      // 按小时间隔生成时间段
      for (let time = start; time < end; time += 60) {
        const current = time % (24 * 60);
        const next = (time + 60) % (24 * 60);

        slots.push(
          `${this.minutesToTime(current)}-${this.minutesToTime(next)}`
        );
      }

      return slots;
    },

    // 时间字符串转分钟数
    timeToMinutes(timeStr) {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    },

    // 分钟数转时间字符串
    minutesToTime(minutes) {
      const hrs = Math.floor(minutes / 60) % 24;
      const mins = minutes % 60;
      return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
    },
    //判断料号是否禁用
    isDisabled(selectID, value) {
      //判断选项是否禁用
      if(selectID === 1) {
        //在第一个选项框中，禁用已被第二个选择框选中的选项
        return this.ruleForm.PartNo2 === value && this.ruleForm.PartNo2 !== '';
      } else {
        //在第二个选项框中，禁用已被第一个选项框选中的选项
        return this.ruleForm.PartNo1 === value && this.ruleForm.PartNo1 !== '';
      }
    },
    //计算实际总产出
    calculateTotal(row) {
      //将输入值转为数字（空值视为0）
      const num1 = parseFloat(row.output1) || 0;
      const num2 = parseFloat(row.output2) || 0;
      //计算结果并保留两位小数
      row.actualOutput = num1 + num2;
    }
  }
}

</script>

<style lang="scss" scoped>
.subBox {
  text-align: center;
  margin-top: 20px;
}
.info-box {
  width: 100%;
  height: 100px;
  overflow: hidden;
  position: relative;
}
.fixed-size1 {
  width: 300px;
  height: 100%;
  margin-left: 105px;
  overflow: auto;
  float: left;
}
.fixed-size2 {
  width: 300px;
  height: 100%;
  margin-left: 23px;
  overflow: auto;
  float: left;
}
.info-item {
  margin-bottom: 10px;
  line-height: 1.4;
}
</style>
